#include "wubi86query.h"

#include <QtSql/QSqlQuery>

Wubi86Query::Wubi86Query(QObject *parent)
    : QObject{parent}
{
    _roots = "";
    _codes = "";

    connect(this, &Wubi86Query::queryChanged, this, &Wubi86Query::newQuery);

    _db = QSqlDatabase::addDatabase("QSQLITE");
    _db.setDatabaseName("./res/86-wubi-encodes.db");
    qDebug() << _db.open();
    qDebug() << _db.tables().join(", ");

    _sqlquery = new QSqlQuery(_db);
}

void Wubi86Query::newQuery() {
    if (_query.length() == 0) {
        _roots = "";
        emit rootsChanged();
        _codes = "";
        emit codesChanged();
        return;
    }

    qDebug() << "from cpp " << _query[0];

    _sqlquery->exec(QString("SELECT * FROM encodes WHERE shape='%1'").arg(_query[0]));
    if (_sqlquery->first()) {
        qDebug() << _sqlquery->value(0).toString();
        qDebug() << _sqlquery->value(1).toString();
        qDebug() << _sqlquery->value(2).toString();

        _roots = _sqlquery->value(2).toString();
        emit rootsChanged();

        _codes = _sqlquery->value(1).toString();
        emit codesChanged();
    }
    else {
        _roots = "";
        emit rootsChanged();
        _codes = "";
        emit codesChanged();
    }
}
